import React, { PureComponent } from 'react';
import {Layout, Spin, message, Empty, Row, Col} from 'antd';
import { WidthProvider, Responsive } from "react-grid-layout";
import _ from "lodash";
import {request} from 'umi';
import style from './index.less'
import '../../../../../node_modules/react-grid-layout/css/styles.css';
import '../../../../../node_modules/react-resizable/css/styles.css';

const ResponsiveReactGridLayout = WidthProvider(Responsive);
const {Content} = Layout;

export default class DragLayout extends PureComponent {

  static defaultProps = {
    cols: { lg: 1, md: 1, sm: 1, xs: 1, xxs: 1 },
  };
  private requestDone: boolean = true;

  constructor(props: any) {
    super(props);
    console.log('props',props)
    this.state = {
      layouts: this.getFromLS("layouts") || {},
      widgets: [],
      loading: true,
      autoRefresh: false,
      currDashBoardId: props.currDashBoardId
    }
    this.getInitData(props.currDashBoardId,props.startTime,props.endTime)
  }


  getInitData = (currDashBoardId: number,startTime: any,endTime: any) => {

    if (!this.requestDone) return message.error('操作太快,请手动刷新')
    this.requestDone = false
    request('/api/dashboardChart/getCharts',{
      method: 'post',
      data : {
        'id': currDashBoardId,
        'startTime': startTime,
        'endTime': endTime,
      }
    }).then( res => {

      if (res.code !== 200){
        this.setState({loading: false})
        return message.error(res.message)
      }
      this.setState({
        widgets: [],
        loading: false,
        empty: false,
      });
      res?.data?.map( (item: any) => {
        this.addChart( item?.res?.data?.OTGraph,item?.dashboardId )
        return true;
      })
      return true;
    }).catch((error)=>{
      if (error?.data?.data?.length === 0){//无图表
        console.log(error.data.message)
        this.setState({
          empty: true,
          autoRefresh: false,
          widgets: [],
        })
      }
    }).finally(()=>{
      this.setState({loading: false})
      this.requestDone = true
      this.state.autoRefresh ? this.getInitData(currDashBoardId,startTime,endTime) : null

    });

    return true
  }

  UNSAFE_componentWillReceiveProps (nextProps: any) {
    this.setState({
      autoRefresh: nextProps.autoRefresh,
      currDashBoardId: nextProps.currDashBoardId,
    })
    const {autoRefresh} = nextProps;
    const {currDashBoardId} = nextProps;
    if (((autoRefresh !== this.state.autoRefresh) && autoRefresh) || currDashBoardId !== this.state.currDashBoardId){
      this.setState({ loading: true })
      this.getInitData(currDashBoardId,nextProps.startTime,nextProps.endTime)
    }
    console.log('nextProps',nextProps)
  }


  addChart = (chart: any,dashboardId: number) => {
    const addItem = {
      x: (this.state.widgets.length * 3) % (this.state.cols || 12),
      y: Infinity, // puts it at the bottom
      w: 2,
      h: 3,
      i: new Date().getTime().toString(),
    };
    this.setState(
      {
        widgets: this.state.widgets.concat({
          ...addItem,
          chart,
          dashboardId,
        }),
      },
    );
  }



  getFromLS(key: any) {
    let ls = {};
    if (global.localStorage) {
      try {
        ls = JSON.parse(global.localStorage.getItem("rgl-8")) || {};
      } catch (e) {
        /*Ignore*/
      }
    }
    return ls[key];
  }

  saveToLS(key, value) {
    if (global.localStorage) {
      global.localStorage.setItem(
        "rgl-8",
        JSON.stringify({
          [key]: value
        })
      );
    }
  }
  generateDOM = () => {
    return _.map(this.state.widgets, (l, i) => {

      const component = (
        l?.chart.map(( item: any,index: any) => {
          // eslint-disable-next-line react/no-array-index-key
          return <img className={l?.chart?.length > 1 ? style.mul_chart_img : style.single_chart_img } src={ item } alt="" key={ index }/>
        })
      )
      return (

        <div key={l.i} data-grid={l}>
          <span className='remove' onClick={this.onRemoveItem.bind(this, i,l?.dashboardId)}>x</span>
          <div className={ style.flex_row }>
            {component}
          </div>

        </div>
      );
    });
  };



  onRemoveItem(i,dashboardId) {
    console.log('dashboardId',dashboardId)
    this.setState({
      widgets: this.state.widgets.filter((item,index) => index !=i)
    });
    request(`/api/dashboardChart/del?id=${dashboardId}`).then((res)=> {
      console.log(res)
    })
  }

  onLayoutChange(layout: any, layouts: any) {
    this.saveToLS("layouts", layouts);
    this.setState({ layouts });
  }


  render() {
    return(
      <Content>
        {
          this.state.loading ?
            <Spin className={style.spinning}
                  size='large'
                  spinning={true}/>
            : this.state.empty ?
            <Empty
              style={{marginTop: 100}}>
            </Empty>
            :
            <ResponsiveReactGridLayout
              className="layout"
              {...this.props}
              layouts={this.state.layouts}
              onLayoutChange={(layout, layouts) =>
                this.onLayoutChange(layout, layouts)
              }
              autoSize={true}
            >

              {this.generateDOM()}
            </ResponsiveReactGridLayout>
        }
      </Content>
    )}
}
